package com.maybach.core.ao.facade.impl;

import com.audi.dubbo.api.brand.vos.ModelVo;
import com.audi.dubbo.api.common.Result;
import com.maybach.common.VO.ApplyForLoanVO;
import com.maybach.common.VO.ContractVO;
import com.maybach.common.VO.LetterInfoVO;
import com.maybach.common.enums.ActLogActorNameEnum;
import com.maybach.common.enums.ActLogBizTypeEnum;
import com.maybach.common.enums.order.*;
import com.maybach.common.model.*;
import com.maybach.common.query.FinanceFlowQuery;
import com.maybach.common.templates.ContractTemplate;
import com.maybach.common.templates.LetterInfoTemplate;
import com.maybach.core.ao.BrandAndSeriesAO;
import com.maybach.core.ao.UserMsgAO;
import com.maybach.core.ao.facade.LoanOrderAOFacade;
import com.maybach.core.form.order.EditLoanOrderForm;
import com.maybach.core.manager.*;
import com.maybach.core.security.AdminUser;
import com.maybach.core.security.AdminUserUtil;
import com.maybach.util.*;
import org.apache.velocity.tools.generic.DateTool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by songshuang on 16/3/4.
 */
@Service
public class LoanOrderAOFacdeImpl implements LoanOrderAOFacade {

    private static final Logger logger = LoggerFactory.getLogger(LoanOrderAOFacdeImpl.class);

    @Autowired
    OrderManager orderManager;
    @Autowired
    LoanOrderManager loanOrderManager;
    @Autowired
    OrderInfoManager orderInfoManager;
    @Autowired
    CarSnapManager carSnapManager;
    @Autowired
    BrandAndSeriesAO brandAndSeriesAO;
    @Autowired
    UserMsgAO userMsgAO;
    @Autowired
    FinanceFlowManager financeFlowManager;
    @Autowired
    UserManager userManager;
    @Autowired
    ShippingOrderManager shippingOrderManager;
    @Autowired
    ActLogManager actLogManager;

    // 机动车销售统一发票(用户票)
    private final Integer UNIFIED_INVOICE = 1;
    // 增值税专用发票(增票)
    private final Integer VAT_SPECIAL_INVOICE = 2;

    private final String EMAIL_TITLE = "发送提车委托函";

    @Override
    public void setOrder(EditLoanOrderForm editLoanOrderForm) throws ParseException {
        OrderDO orderDO = orderManager.selectByPrimaryKey(editLoanOrderForm.getOrderId());
        if (StringUtil.isNotEmpty(editLoanOrderForm.getTotalAmount())) {
            orderDO.setTotalAmount(PriceUtil.convertPriceYuanWithComma(editLoanOrderForm.getTotalAmount()));
        }
        if (StringUtil.isNotEmpty(editLoanOrderForm.getDespositAmount())) {
            orderDO.setDespositAmount(PriceUtil.convertPriceYuanWithComma(editLoanOrderForm.getDespositAmount()));
        }
//        orderDO.setDespositImgs(ImgUrlUtil.mergeList(editLoanOrderForm.getDespositImgs()));
//        orderDO.setDaifuImgs(ImgUrlUtil.mergeList(editLoanOrderForm.getDaifuImgs()));
        orderDO.setCarNum(editLoanOrderForm.getCarNum());
        orderDO.setStatus(OrderStatusEnum.comfirmed.getCode());
        orderDO.setBuyerId(editLoanOrderForm.getBuyerId());
        if (editLoanOrderForm.getDespositPayTime() != null &&
                !"".equals(editLoanOrderForm.getDespositPayTime())) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            orderDO.setDespositPayTime(sdf.parse(editLoanOrderForm.getDespositPayTime()));
        }
        orderManager.updateByPrimaryKeySelective(orderDO);
    }

    @Override
    public void setLoanOrder(EditLoanOrderForm editLoanOrderForm) throws ParseException {
        LoanOrderDO loanOrderDO = loanOrderManager.selectByPrimaryKey(editLoanOrderForm.getId());
        if (StringUtil.isNotEmpty(editLoanOrderForm.getDespositAmount())) {
            loanOrderDO.setDespositAmount(PriceUtil.convertPriceYuanWithComma(editLoanOrderForm.getDespositAmount()));
        }
        if (StringUtil.isNotEmpty(editLoanOrderForm.getTotalAmount())) {
            loanOrderDO.setTotalAmount(PriceUtil.convertPriceYuanWithComma(editLoanOrderForm.getTotalAmount()));
        }
        if (StringUtil.isNotEmpty(editLoanOrderForm.getDespositAmount())) {
            loanOrderDO.setDespositAmount(PriceUtil.convertPriceYuanWithComma(editLoanOrderForm.getDespositAmount()));
        }
        if (StringUtil.isNotEmpty(editLoanOrderForm.getMarginAmount())) {
            loanOrderDO.setMarginAmount(PriceUtil.convertPriceYuanWithComma(editLoanOrderForm.getMarginAmount()));
        }
        if (StringUtil.isNotEmpty(editLoanOrderForm.getLoanAmount())) {
            loanOrderDO.setLoanAmount(PriceUtil.convertPriceYuanWithComma(editLoanOrderForm.getLoanAmount()));
        }
        int originStatus = loanOrderDO.getStatus();
        if(originStatus == LoanOrderStatusEnum.init.getCode()){
            loanOrderDO.setStatus(LoanOrderStatusEnum.comfirmed.getCode());
        }
        loanOrderDO.setManager(editLoanOrderForm.getManager());
        loanOrderDO.setMemo(editLoanOrderForm.getMemo());

        BigDecimal rate = editLoanOrderForm.getInterestRate();
        if (rate != null) {
            loanOrderDO.setInterestRate(rate);
        }

        loanOrderManager.updateByPrimaryKeySelective(loanOrderDO);

        if(originStatus == LoanOrderStatusEnum.init.getCode()) {
            userMsgAO.confirmOrder(loanOrderDO);
        }
    }

    @Override
    public void setOrderInfo(EditLoanOrderForm editLoanOrderForm, List<OrderInfoDO> list) {
        OrderInfoDO orderInfoDO = new OrderInfoDO();
        orderInfoDO.setBizId(editLoanOrderForm.getId());
        orderInfoDO.setBizType(InfoBizTypeEnum.LoanOrder.name());
        List<String> despositImgs = editLoanOrderForm.getDespositImgs();
        List<String> daifuImgs = editLoanOrderForm.getDaifuImgs();
        LoanOrderDO loanOrderDO = loanOrderManager.selectByPrimaryKey(editLoanOrderForm.getId());

        if (list == null || list.size() == 0) {
            orderInfoDO.setInfoStatus(InfoStatusEnum.init.getStatus());
            // 定金凭证
            if (despositImgs != null) {
                orderInfoDO.setInfoValue(ImgUrlUtil.mergeList(despositImgs));
                orderInfoDO.setInfoType(InfoTypeEnum.DepositImgs.name());
                orderInfoManager.insertSelective(orderInfoDO);
                //userMsgAO.passInfo(loanOrderDO, InfoTypeEnum.DepositImgs);
            }
            // 代付凭证
            if (daifuImgs != null) {
                orderInfoDO.setInfoValue(ImgUrlUtil.mergeList(editLoanOrderForm.getDaifuImgs()));
                orderInfoDO.setInfoType(InfoTypeEnum.DaifuImgs.name());
                orderInfoManager.insertSelective(orderInfoDO);
                //userMsgAO.passInfo(loanOrderDO, InfoTypeEnum.DaifuImgs);
            }
        } else {
            boolean depositImageFlag = false;
            boolean daifuImageFlag = false;
            for (OrderInfoDO orderInfoDOItem: list) {
                if (InfoTypeEnum.DepositImgs.name().equals(orderInfoDOItem.getInfoType())) {
                    depositImageFlag = true;
                    //orderInfoDOItem.setInfoStatus(InfoStatusEnum.pass.getStatus());
                    orderInfoDOItem.setInfoValue(ImgUrlUtil.mergeList(editLoanOrderForm.getDespositImgs()));
                    orderInfoManager.updateByPrimaryKeySelective(orderInfoDOItem);
                }
                // 代付凭证
                if (InfoTypeEnum.DaifuImgs.name().equals(orderInfoDOItem.getInfoType())) {
                    daifuImageFlag = true;
                    //orderInfoDOItem.setInfoStatus(InfoStatusEnum.pass.getStatus());
                    orderInfoDOItem.setInfoValue(ImgUrlUtil.mergeList(editLoanOrderForm.getDaifuImgs()));
                    orderInfoManager.updateByPrimaryKeySelective(orderInfoDOItem);
                }
            }
            // 判断当其中有一个图片没有上传的时候,进行上传信息
            if (!depositImageFlag) {
                orderInfoDO.setInfoValue(ImgUrlUtil.mergeList(despositImgs));
                orderInfoDO.setInfoType(InfoTypeEnum.DepositImgs.name());
                orderInfoManager.insertSelective(orderInfoDO);
                //userMsgAO.passInfo(loanOrderDO, InfoTypeEnum.DepositImgs);
            }
            if (!daifuImageFlag) {
                orderInfoDO.setInfoValue(ImgUrlUtil.mergeList(editLoanOrderForm.getDaifuImgs()));
                orderInfoDO.setInfoType(InfoTypeEnum.DaifuImgs.name());
                orderInfoManager.insertSelective(orderInfoDO);
                //userMsgAO.passInfo(loanOrderDO, InfoTypeEnum.DaifuImgs);
            }

        }
    }

    @Override
    public void setCarSnap(EditLoanOrderForm editLoanOrderForm, CarSnapDO carSnapDO) {
        String modelName = "";
        if (editLoanOrderForm.getModelId().intValue() == -1) {
            modelName = editLoanOrderForm.getModelName();
        } else {
            Result result = brandAndSeriesAO.getModelsBySeriesId(editLoanOrderForm.getSeriesId());
            if (result.isSuccess()) {
                List<ModelVo> modelVoList = (List) result.getData();
                for (ModelVo modelVo : modelVoList) {
                    if (modelVo.getModelId().longValue() == editLoanOrderForm.getModelId()) {
                        modelName = modelVo.getModelName();
                    }
                }
            }
        }
        if (carSnapDO == null) {
            carSnapDO = new CarSnapDO();
            carSnapDO.setModelName(modelName);
            carSnapDO.setOrderId(editLoanOrderForm.getOrderId());
            carSnapDO.setLoanOrderId(editLoanOrderForm.getId());
            carSnapDO.setModelId(editLoanOrderForm.getModelId());
            carSnapDO.setBrandId(editLoanOrderForm.getBrandId());
            carSnapDO.setSeriesId(editLoanOrderForm.getSeriesId());
            carSnapDO.setSpecId(editLoanOrderForm.getCarOriginType());
            carSnapDO.setOuterColorName(editLoanOrderForm.getOutColor());
            carSnapDO.setInnerColorName(editLoanOrderForm.getInnerColor());
            carSnapManager.insertSelective(carSnapDO);
        } else {
            carSnapDO.setModelName(modelName);
            carSnapDO.setModelId(editLoanOrderForm.getModelId());
            carSnapDO.setBrandId(editLoanOrderForm.getBrandId());
            carSnapDO.setSeriesId(editLoanOrderForm.getSeriesId());
            carSnapDO.setSpecId(editLoanOrderForm.getCarOriginType());
            carSnapDO.setOuterColorName(editLoanOrderForm.getOutColor());
            carSnapDO.setInnerColorName(editLoanOrderForm.getInnerColor());
            carSnapManager.updateByPrimaryKeySelective(carSnapDO);
        }
    }

    @Override
    public List<ApplyForLoanVO> getContractInfo(Long id) {
        List<ApplyForLoanVO> applyForLoanVOList = new ArrayList<>();

        FinanceFlowQuery query = new FinanceFlowQuery();
        query.createCriteria().andLoanOrderIdEqualTo(id);

        List<FinanceFlowDO> list = financeFlowManager.selectByQuery(query);
        // 订单宝的信息
        LoanOrderDO loanOrderDO = loanOrderManager.selectByPrimaryKey(id);
        Long orderId = loanOrderDO.getOutOrderId();
        //
        Long buyerId = loanOrderDO.getBuyerId();
        Long providerId = loanOrderDO.getProviderId();
        UserDO userDO = userManager.selectByPrimaryKey(buyerId);
        UserDO providerDO = userManager.selectByPrimaryKey(providerId);

        OrderDO orderDO = orderManager.selectByPrimaryKey(orderId);

        CarSnapDO carSnapDO = carSnapManager.selectByLoanOrderId(id);

        setApplyInfo(applyForLoanVOList, list, loanOrderDO, userDO, providerDO, orderDO, carSnapDO);

        return applyForLoanVOList;
    }

    @Override
    public LetterInfoVO getLetterInfo(Long id) {
        return setLetterInfo(id);
    }

    @Override
    public void createContractPDF(String path, Long id, HttpServletResponse response) {
        // 暂时不用填写数据
//        ContractVO contractVO = setContractInfo(id);
        ContractVO contractVO = new ContractVO();
        ContractTemplate contractTemplate = new ContractTemplate(contractVO);
        PdfUtil.createPDF(response, path, contractTemplate.getTemplate(), "车辆代购服务合同");
    }

    @Override
    public ContractVO createContract(Long id) {
        ContractVO contractVO = new ContractVO();
        return contractVO;
        // 暂时不用填写数据
//        return setContractInfo(id);
    }

    @Override
    public Boolean sendLetter(Long id) {
        LetterInfoVO letterInfoVO = setLetterInfo(id);
        LetterInfoTemplate letterInfoTemplate = new LetterInfoTemplate(letterInfoVO);
        String address = letterInfoVO.getEmailAddress();
        String contents = letterInfoTemplate.getTemplate();
        if (address == null || "".equals(address)) {
            logger.error("发送失败,邮箱不能为空: loan_order_id = " + id);
            return false;
        }
        Boolean result = SendEmailUtil.sendWithHtml(address, EMAIL_TITLE, contents);
        return result;
    }

    private void setApplyInfo(List<ApplyForLoanVO> applyForLoanVOList, List<FinanceFlowDO> list,
                              LoanOrderDO loanOrderDO, UserDO userDO, UserDO providerDO, OrderDO orderDO, CarSnapDO carSnapDO) {

        String providerName = "";
        if (StringUtil.isNotEmpty(loanOrderDO.getProviderName())) {
            if (providerDO != null && StringUtil.isNotEmpty(providerDO.getRealName())) {
                providerName = providerDO.getRealName();
            }
        }
        for (FinanceFlowDO financeFlowDO: list) {
            ApplyForLoanVO applyForLoanVO = new ApplyForLoanVO();
            if (loanOrderDO != null) {
                applyForLoanVO.setApplyTime(loanOrderDO.getGmtCreate().toString());
                applyForLoanVO.setManagerName(loanOrderDO.getManager());
                applyForLoanVO.setLoanOrderId(loanOrderDO.getId());
            }
            if (userDO != null) {
                applyForLoanVO.setApplyUser(userDO.getRealName());
            }
            if (orderDO != null) {
                applyForLoanVO.setOrderNo(orderDO.getOrderNo());
            }
            if (carSnapDO != null) {
                applyForLoanVO.setModelName(carSnapDO.getModelName());
            }
            applyForLoanVO.setApplyTime(loanOrderDO.getGmtCreate().toString());
            applyForLoanVO.setAccountName(financeFlowDO.getAccountName());
            applyForLoanVO.setAccountNo(financeFlowDO.getAccountNo());
            applyForLoanVO.setTotalAmount(financeFlowDO.getAmount());
            applyForLoanVO.setOpeningBank(financeFlowDO.getOpeningBank());
            applyForLoanVO.setProviderName(providerName);
            applyForLoanVOList.add(applyForLoanVO);
        }
    }

    public LetterInfoVO setLetterInfo(Long id) {
        LoanOrderDO loanOrderDO = loanOrderManager.selectByPrimaryKey(id);
        Long userId = loanOrderDO.getBuyerId();
        Long dealerId = loanOrderDO.getDealerId(); // 经销商Id
        UserDO userDO = userManager.selectByPrimaryKey(userId);
        UserDO dealerDo = userManager.selectByPrimaryKey(dealerId);
        CarSnapDO carSnapDO = carSnapManager.selectByLoanOrderId(id);
        LetterInfoVO letterInfoVO = new LetterInfoVO();

        String userName = "";
        String certNo = "";
        String mobile = "";
        String modelName = "";
        String carUnique = "";
        String email = "";
        if (dealerDo != null) {
            email = dealerDo.getEmailAddress();
        }
        if (userDO != null) {
            if (userDO.getRealName() != null) {
                userName = userDO.getRealName();
            }
            if (userDO.getMobile() != null) {
                mobile = userDO.getMobile();
            }
            if (userDO.getCertNo() != null) {
                certNo = userDO.getCertNo();
            }
        }
        if (carSnapDO != null) {
            if (carSnapDO.getModelName() != null) {
                modelName = carSnapDO.getModelName();
            }
        }
        // 获取车架号
        ShippingOrderDO shippingOrderDO = shippingOrderManager.selectByOutOrderId(id);
        if (shippingOrderDO != null && !"".equals(shippingOrderDO.getCarUnique())) {
            carUnique = shippingOrderDO.getCarUnique();
        }

        letterInfoVO.setUserName(userName);
        letterInfoVO.setMobile(mobile);
        letterInfoVO.setIdentityId(certNo);
        letterInfoVO.setEmailAddress(email);
        letterInfoVO.setCarUnique(carUnique);
        letterInfoVO.setModelName(modelName);
        letterInfoVO.setCheckModelName(modelName);
        letterInfoVO.setCheckCarUnique(carUnique);
        letterInfoVO.setLoanOrderId(id);

        return letterInfoVO;
    }

    public ContractVO setContractInfo(Long id) {
        ContractVO contractVo = new ContractVO();
        DateTool dateTool = new DateTool();

        CarSnapDO carSnapDo = carSnapManager.selectByLoanOrderId(id);
        if (carSnapDo != null) {
            if (StringUtil.isNotEmpty(carSnapDo.getModelName())) {
                contractVo.setModelName(carSnapDo.getModelName());
            }
            if (StringUtil.isNotEmpty(carSnapDo.getOuterColorName())) {
                contractVo.setOutColor(carSnapDo.getOuterColorName());
            }
            if (StringUtil.isNotEmpty(carSnapDo.getInnerColorName())) {
                contractVo.setInnerColor(carSnapDo.getInnerColorName());
            }
        }

        LoanOrderDO loanOrderDo = loanOrderManager.selectByPrimaryKey(id);
        if (loanOrderDo != null) {
            if (StringUtil.isNotEmpty(loanOrderDo.getDealerName())) {
                contractVo.setDealerName(loanOrderDo.getDealerName());
            }
            if (loanOrderDo.getLoanAmount() != null) {
                contractVo.setLoanAmount(getAmount(loanOrderDo.getLoanAmount()));
            }
            if (StringUtil.isNotEmpty(loanOrderDo.getProviderName())) {
                contractVo.setProviderName(loanOrderDo.getProviderName());
            }
            if (loanOrderDo.getDespositAmount() != null) {
                contractVo.setDepositAmount(loanOrderDo.getDespositAmount().toString());
            }
            if (loanOrderDo.getTotalAmount() != null) {
                contractVo.setPrice(getAmount(loanOrderDo.getTotalAmount()));
            }
            if (loanOrderDo.getMarginAmount() != null) {
                contractVo.setMarginAmount(getAmount(loanOrderDo.getMarginAmount()));
            }
            if (StringUtil.isNotEmpty(loanOrderDo.getEmail())) {
                contractVo.setPartBEmail(loanOrderDo.getEmail());
            }
        }

        Long orderId = loanOrderDo.getOutOrderId();
        OrderDO orderDo = orderManager.selectByPrimaryKey(orderId);
        if (orderDo != null) {
            if (orderDo.getDespositPayTime() != null) {
                String payTime = dateTool.format("yyyy-MM-dd HH:mm:ss", orderDo.getDespositPayTime());
                contractVo.setDepositTime(payTime);
            }
            // 获取发票类型
            if (InvoiceTypeEnum.unifiedInvoice.name().equals(orderDo.getInvoiceType())) {
                // 机动车销售统一发票(用户票)
                contractVo.setInvoiceType(UNIFIED_INVOICE);
            }
            if (InvoiceTypeEnum.vatSpecialInvoice.name().equals(orderDo.getInvoiceType())) {
                // 增值税专用发票(增票)
                contractVo.setInvoiceType(VAT_SPECIAL_INVOICE);
            }
        }

        ShippingOrderDO shippingOrderDO = shippingOrderManager.selectByOutOrderId(id);

        if (shippingOrderDO != null) {
            if (StringUtil.isNotEmpty(shippingOrderDO.getShippingContact())) {
                contractVo.setShippingContacts(shippingOrderDO.getShippingContact());
            }
            if (StringUtil.isNotEmpty(shippingOrderDO.getShippingPhone())) {
                contractVo.setShippingPhone(shippingOrderDO.getShippingPhone());
            }
            if (StringUtil.isNotEmpty(shippingOrderDO.getTocity())) {
                contractVo.setShippingDest(shippingOrderDO.getTocity());
            }
            if (StringUtil.isNotEmpty(shippingOrderDO.getLogisticsCompany())) {
                contractVo.setShippingCompany(shippingOrderDO.getLogisticsCompany());
            }
            if (shippingOrderDO.getAmount() != null && !"".equals(shippingOrderDO.getAmount())) {
                contractVo.setShippingAmount(getAmount(shippingOrderDO.getAmount()));
            }
            if (StringUtil.isNotEmpty(shippingOrderDO.getShippingPlace())) {
                contractVo.setShippingPlace(shippingOrderDO.getShippingPlace());
            }
            if (shippingOrderDO.getShippingTime() != null) {
                String shippingTime = dateTool.format("yyyy-MM-dd HH:mm:ss", shippingOrderDO.getShippingTime());
                contractVo.setShippingTime(shippingTime);
            }
        }

        FinanceFlowQuery query = new FinanceFlowQuery();
        query.createCriteria().andLoanOrderIdEqualTo(id).andBizTypeEqualTo(FinanceBizTypeEnum.ProviderPay.name());
        List<FinanceFlowDO> list = financeFlowManager.selectByQuery(query);

        if (list != null && list.size() > 0) {
            for (FinanceFlowDO financeFlowDO: list) {
                if ("company".equals(financeFlowDO.getFinanceType())) { // 公司账号
                    contractVo.setSupplierPublicAccount(financeFlowDO.getAccountName());
                    contractVo.setSupplierPublicAccountNo(financeFlowDO.getAccountNo());
                    if (financeFlowDO.getAmount() != null) {
                        contractVo.setSupplierAmount(getAmount(financeFlowDO.getAmount()));
                    }
                    String payTime = dateTool.format("yyyy-MM-dd HH:mm:ss", financeFlowDO.getPayTime());
                    contractVo.setLoanStartTime(payTime);
                }
                if ("person".equals(financeFlowDO.getFinanceType())) {
                    contractVo.setSupplierPrivateAccount(financeFlowDO.getAccountName());
                    contractVo.setSupplierPrivateAccountNo(financeFlowDO.getAccountNo());
                    if (financeFlowDO.getAmount() != null) {
                        contractVo.setSupplierPrivateAmount(getAmount(financeFlowDO.getAmount()));
                    }
                }
            }
        }

        return contractVo;
    }

    private String getAmount(Long amount) {
        StringBuilder supplierPrivateAmount = new StringBuilder();
        supplierPrivateAmount.append(PriceUtil.formatCNY(amount));
        supplierPrivateAmount.append("元");
        return supplierPrivateAmount.toString();
    }

    public void insertLog(String bizType, Long bizId, String detail, String title) {

        try {
            AdminUser user = AdminUserUtil.getUser();
            String actorName = user.getRealName();
            Long actorId = user.getAdminId();
            String actorLabel = user.getDepartmentName();

            ActLogDO actLogDO = new ActLogDO();
            actLogDO.setBizType(bizType);
            actLogDO.setBizId(bizId);
            actLogDO.setActorName(actorName);
            actLogDO.setActorId(actorId);
            actLogDO.setActorLabel(actorLabel);
            actLogDO.setActDetail(detail);
            actLogDO.setActTitle(title);

            actLogManager.insertSelective(actLogDO);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
